import axios from 'axios'
import errorCode from './errorCode'
import { message } from 'ant-design-vue'

const Toast = message

// 请求拦截器
axios.interceptors.request.use(
  config => {
    if (config.method === 'get') {
      config.data = { ...config.data, unused: 0 } // 这个是关键点，加入这行就可以了,解决get,请求添加不上Content-Type
    }
    return config
  },
  error => {
    return Promise.error(error)
  }
)

export const request = async (url, options) => {
  const baseUrl = ''

  // 请求之前添加请求头
  options.headers = options.headers || {}
  let userInfo = {}
  try {
    userInfo = JSON.parse(sessionStorage.getItem('UserInfo')) || {}
  } catch (e) {}
  options.headers['session-key'] = userInfo.sessionKey || ''

  // 发起请求
  const response = await axios({
    method: options.method,
    url: `${baseUrl + url}`,
    headers: options.headers,
    timeout: options.timeout || 60000,
    params: options.params,
    data: options.data,
  })

  // 请求后处理
  const res = response.data
  const { toastError = true } = options || {}
  // const { code, result, message, success } = res || {}
  const { code, message, msg, success } = res || {}
  if (code === 200 || success) {
    return res
  } else if (code === 20001) {
    // TODO 未登录
  } else {
    const _msg = errorCode.getErrorMsg(code) || message || msg
    toastError && Toast.error(_msg)
    return Promise.reject(res)
  }
}
export default {
  get(url, options = {}) {
    return request(
      url,
      Object.assign(options, {
        method: 'get',
      })
    )
  },

  post(url, options = {}) {
    return request(
      url,
      Object.assign(options, {
        method: 'post',
      })
    )
  },

  export(url, params) {
    // 如果没有域名默认配置baseURI
    if (!/https?:\/\//i.test(url)) {
      const baseUrl = process.env.VUE_APP_BASE_URL || ''
      url = baseUrl + url
    }
    const paramArr = []
    for (const key in params) {
      if (!params[key]) {
        continue
      }
      if (typeof params[key] === 'object') {
        params[key] = encodeURIComponent(JSON.stringify(params[key]))
      }
      paramArr.push(key + '=' + params[key])
    }

    if (paramArr.length !== 0) {
      if (url.indexOf('?') >= 0) {
        url += '&'
      } else {
        url += '?'
      }
      url += paramArr.join('&')
    }

    const saveLink = document.createElement('a')
    saveLink.href = url
    saveLink.target = '_blank'
    saveLink.click()
  },
}
